package org.aiforum.common;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/*
 * 缓存上下文
 */
public class CacheContext {
    
	//私有化对象
	private  CacheContext(){}
	
	//建立缓存容器
	private static Map<String,CacheObject> cache=Collections.synchronizedMap(new HashMap<String,CacheObject>());
	
	//提供方法操作缓存
	
	/*
	 * 设置缓存
	 */
	public static boolean setCache(String key,Object object,long time){
		CacheObject cacheObject=new CacheObject(object,time);
		cache.put(key, cacheObject);
		return true;
	}
	
	/*
	 * 获取缓存
	 */
	public static <T> T getCache(String key,Class<T> clz){
		//先判断缓存是否存在
		if(cache.containsKey(key)){
			//获取缓存对象
			CacheObject cacheObject=cache.get(key);
			//检查缓存是否有效
			long currentTime=System.currentTimeMillis();
			long timeout=cacheObject.getTimeout();
			
			//如果当前时间大于缓存时间则无效
			if(currentTime>timeout){
				//移除过期缓存数据
				delCache(key);
				return null;
			}
			return (T)cacheObject.getData();
		}
		
		return null;
	}

	public static boolean delCache(String key){
		cache.remove(key);
		return true;
	}
}
